Dismissing a presented view

This example demonstrates how to programmatically dismiss a presented view using the Navigation.useDismiss hook. It is useful when you want to close a custom view in response to user interaction, such as tapping a button or a text label.


Purpose

You will learn how to:

  • Access the dismiss function via Navigation.useDismiss
  • Call the dismiss function to close the currently presented view
  • Safely exit the script using Script.exit to avoid memory leaks

Example Code

1import { Navigation, NavigationStack, Script, Text, VStack } from "scripting"
2
3function View() {
4  // Access the `dismiss` function of the context.
5  const dismiss = Navigation.useDismiss()
6
7  return <NavigationStack>
8    <VStack
9      navigationTitle={"Dismiss a view"}
10    >
11      <Text
12        foregroundStyle={'link'}
13        onTapGesture={() => {
14          dismiss()
15        }}
16      >Tap and dismiss</Text>
17    </VStack>
18  </NavigationStack>
19}
20
21async function run() {
22  await Navigation.present({
23    element: <View />
24  })
25
26  // Avoiding memory leaks.
27  Script.exit()
28}
29
30run()

Key Concepts

This hook returns the dismiss function from the current view context. When called, it dismisses the view presented via Navigation.present().

When to use it

  • To manually close a presented UI view
  • As part of form submission, cancellation, or navigation control logic

Example usage

In the example, a tappable Text is rendered:

1<Text
2  foregroundStyle={'link'}
3  onTapGesture={() => {
4    dismiss()
5  }}
6>
7  Tap and dismiss
8</Text>

Tapping the text triggers dismiss(), closing the view.


Best Practices

  • Always call Script.exit() after Navigation.present() completes to avoid memory leaks.
  • Wrap your view in NavigationStack to support title bars and navigation behavior.
  • Ensure useDismiss is only used inside the component tree presented via Navigation.present().

Result

This script will present a simple view with a link-style text labeled “Tap and dismiss”. When the user taps it, the view will close.